<script lang="ts" setup>
import dayjs from 'dayjs'
import type { SkuListItem } from '../set_Sku_data'
import type { GoodsItemModel, GoodsItemskuListModel, MyGoodsListSendModel } from '@/api/goods'
import type { CategoryGetReturnItemModel } from '@/api/category'
import { myGoodsDetail, myGoodsList } from '@/api/goods'
import { categoryGetTwo } from '@/api/category'
import { goodsSkuListDeleteList, goodsSkuListModifyList } from '@/api/goodsSkuList'
const router = useRouter()
onMounted(() => {
  getCategoryTwo()
  getList()
})
// 获取商品列表数据
const listQuery = ref<MyGoodsListSendModel>({
  page: 1,
  size: 10,
  categoryTwoId: null,
  value: '',
  total: 0,
})
const goodsData = ref<GoodsItemModel[]>([])
async function getList() { // 获取商品数据
  const { code, data } = await myGoodsList(listQuery.value)
  if (code === 0) {
    goodsData.value = data!.list
    listQuery.value.total = data!.total
  }
}
// 分类筛选回调
function categoryChange(value: number) {
  listQuery.value.categoryTwoId = value
  getList()
}

// 表格分类回显文字部分
const categoryTwoData = ref<CategoryGetReturnItemModel[]>()
async function getCategoryTwo() { // 获取二级分类
  const { data, code } = await categoryGetTwo()
  if (code === 0)
    categoryTwoData.value = data
}
function categoryFilter(parentId: number | string) {
  if (categoryTwoData.value?.length === 0)
    return '空'
  let categoryName = ''
  categoryTwoData.value?.forEach((item) => {
    if (item.id === parentId)
      categoryName = item.name
  })
  return categoryName
}

// 模态框
interface Dialog<T=SkuListItem, K=GoodsItemskuListModel> {
  visible: boolean
  title: string
  skuListItem: T[]
  skuData?: K[]
  goodsId?: number
}
const dialog = ref<Dialog>({
  visible: false,
  title: '',
  skuListItem: [], // 规格列表数组
  skuData: [], // 规格信息数组
})
async function openDialog(goodsId: number) { // 打开模态框
  const { setSku_list } = await import('./../set_Sku_data')
  const { code, data } = await myGoodsDetail({ goodsId })
  if (code === 0) {
    dialog.value.title = data!.name
    dialog.value.goodsId = goodsId
    dialog.value.visible = true
    dialog.value.skuData = data?.skuList
    // 无规格商品
    if (data?.none_sku)
      dialog.value.skuListItem = setSku_list(data as GoodsItemModel, 'none')
    // 多规格商品
    else
      dialog.value.skuListItem = setSku_list(data as GoodsItemModel, '')
  }
}

async function removeSkuList(skuListId: number, goodsId: number) { // 删除规格列表
  const { code, msg } = await goodsSkuListDeleteList({ ids: skuListId.toString() })
  if (code === 0) {
    window.$message?.success(msg)
    openDialog(goodsId) // 刷新数据
  }
}

// 规格列表修改表单模态框
interface SkuDialog {
  visible: boolean
  title: string
  price: string // sku价格
  skuValue: { [propName: string]: any } // 已选择的sku规格
  parentId: number // 商品id
  id?: number // 当前sku Id
  stock_num?: number // sku当前库存
}

const skuDialog = ref<SkuDialog>({
  visible: false,
  title: '',
  price: '',
  skuValue: {},
  parentId: 0,
})

function openSkuDailog(row: SkuListItem) { // 打开规格列表模态框
  skuDialog.value.visible = true
  skuDialog.value.title = '修改规格信息'
  skuDialog.value.id = row._id
  skuDialog.value.parentId = row.goods_id
  skuDialog.value.stock_num = row.stock
  skuDialog.value.price = row.price
  // 初始化已选择的sku ID (vId)
  row.indexList.forEach((item) => {
    dialog.value.skuData![item.parentIndex].vId = dialog.value.skuData![item.parentIndex].v[item.sonIndex].id
    skuDialog.value.skuValue[dialog.value.skuData![item.parentIndex].k_s] = dialog.value.skuData![item.parentIndex].v[item.sonIndex].id
  })
}
function closeSkuDialog() {
  skuDialog.value = {
    visible: false,
    title: '',
    price: '',
    skuValue: {},
    parentId: 0,
    stock_num: 0,
    id: 0,
  }
}
function skuFormSkuChange(item: GoodsItemskuListModel, vId: number) { // 选择单项规格回调
  item.vId = vId
  skuDialog.value.skuValue[item.k_s] = item.vId
}
async function submitSkuModal() { // 规格信息模态框提交
  const integral = /^\+?[1-9]\d*$/
  const price = /^-?\d{1,3}(,\d{3})*(\.\d{1,2})?$/
  if (!skuDialog.value.price || !price.test(skuDialog.value.price))
    return window.$message?.warning('请输入正确的价格')
  if (!skuDialog.value.stock_num || !integral.test(skuDialog.value.stock_num.toString()))
    return window.$message?.warning('请输入正确的库存数量')
  if (dialog.value.skuData?.length !== Object.keys(skuDialog.value.skuValue).length)
    return window.$message?.warning('请继续选择规格')

  const { code, msg } = await goodsSkuListModifyList({
    id: skuDialog.value.id,
    parentId: skuDialog.value.parentId,
    stock_num: skuDialog.value.stock_num,
    price: skuDialog.value.price,
    ...skuDialog.value.skuValue,
  })
  if (code === 0) {
    window.$message?.success(msg)
    openDialog(skuDialog.value.parentId)
    closeSkuDialog()
  }
  else {
    window.$message?.error(msg)
    closeSkuDialog()
  }
}
// 跳转商品修改||详情页
function toGoodsPage(goodsId: number, type: string) {
  router.push({
    name: `Goods${type}`,
    params: { goodsId },
  })
}
</script>

<template>
  <AppPage class="goodsList">
    <n-space align="center" justify="space-between" mb20>
      <span font-bold text-18>商品列表</span>
      <n-space align="center">
        <span>筛选</span>
        <Ccascader v-model:categoryId="listQuery.categoryTwoId" w-200 @update:categoryId="categoryChange" />
      </n-space>
    </n-space>
    <n-grid x-gap="15" :cols="9" bg-white p-10 text-14 b-rd-5 dark:bg-dark>
      <n-gi f-c-c font-bold>
        上架时间
      </n-gi>
      <n-gi f-c-c font-bold>
        商品封面
      </n-gi>
      <n-gi f-c-c font-bold>
        商品名称
      </n-gi>
      <n-gi f-c-c font-bold>
        商品标签
      </n-gi>
      <n-gi f-c-c font-bold>
        商品类别
      </n-gi>
      <n-gi f-c-c font-bold>
        商品库存
      </n-gi>
      <n-gi f-c-c font-bold>
        规格信息
      </n-gi>
      <n-gi span="2" f-c-c font-bold>
        操作
      </n-gi>
    </n-grid>
    <template v-if="goodsData.length > 0">
      <n-grid v-for="item in goodsData" :key="item.id" x-gap="15" :cols="9" bg-white p-10 text-14 b-rd-5 mt-10 dark:bg-dark>
        <n-gi f-c-c>
          {{ dayjs(item.createTime || new Date()).format('YYYY-MM-DD HH:mm') }}
        </n-gi>
        <n-gi f-c-c>
          <Cimage
            lazy
            root=".goodsList"
            width="80"
            height="80"
            :src="item.iconId[0].url"
          />
        </n-gi>
        <n-gi f-c-c>
          <n-ellipsis :line-clamp="2">
            {{ item.name || '未填写' }}
          </n-ellipsis>
        </n-gi>
        <n-gi f-c-c>
          <n-tag :bordered="false">
            {{ item.hot }}
          </n-tag>
        </n-gi>
        <n-gi f-c-c font-bold>
          {{ categoryFilter(item.parentId) }}
        </n-gi>
        <n-gi f-c-c>
          {{ item.stock_num }}
        </n-gi>
        <n-gi f-c-c>
          <n-tag v-if="item.none_sku" type="error">
            无规格商品
          </n-tag>
          <n-tag v-else type="info">
            多规格商品
          </n-tag>
        </n-gi>
        <n-gi span="2" f-c-c flex-wrap>
          <n-button :disabled="item.none_sku ? true : false" size="small" text-14 ml-5 mt5 @click="openDialog(item.id)">
            <template #icon>
              <icon-ri:search-line />
            </template>
            规格列表
          </n-button>
          <n-button size="small" type="tertiary" text-14 ml-5 mt5 @click="toGoodsPage(item.id, 'Detail')">
            <template #icon>
              <icon-ri:search-line />
            </template>
            查 看
          </n-button>
          <n-button type="info" size="small" text-14 ml-5 mt5 @click="toGoodsPage(item.id, 'Modify')">
            <template #icon>
              <icon-mdi:square-edit-outline />
            </template>
            编 辑
          </n-button>
        </n-gi>
      </n-grid>
      <Cpagination
        v-model:page="listQuery.page"
        :total="listQuery.total"
        :page-size="listQuery.size"
        @update-page="getList"
      />
    </template>
    <template v-else>
      <div bg-white p-10 text-14 font-bold b-rd-5 mt-10 dark:bg-dark f-c-c pt-20 pb-20>
        暂无数据
      </div>
    </template>
  </AppPage>
  <Cdialog v-model:visible="dialog.visible" :title="dialog.title">
    <n-grid x-gap="15" :cols="6" bg-white p-10 text-14 b-rd-5 dark:bg-dark>
      <n-gi f-c-c font-bold>
        规格封面
      </n-gi>
      <n-gi f-c-c font-bold>
        规格信息
      </n-gi>
      <n-gi f-c-c font-bold>
        价格
      </n-gi>
      <n-gi f-c-c font-bold>
        库存
      </n-gi>
      <n-gi span="2" f-c-c font-bold>
        操作
      </n-gi>
    </n-grid>
    <n-grid v-for="item in dialog.skuListItem" :key="item._id" x-gap="15" :cols="6" bg-white p-5 text-14 b-rd-5 mt-5 dark:bg-dark>
      <n-gi f-c-c>
        <Cimage
          width="50"
          height="50"
          :src="item.image"
        />
      </n-gi>
      <n-gi f-c-c>
        {{ item.sku_name_arr.toString() }}
      </n-gi>
      <n-gi f-c-c>
        ￥{{ item.price }}
      </n-gi>
      <n-gi f-c-c>
        {{ item.stock }}
      </n-gi>
      <n-gi span="2" f-c-c>
        <n-button type="info" size="small" text-14 ml-5 mt5 @click="openSkuDailog(item)">
          <template #icon>
            <icon-mdi:square-edit-outline />
          </template>
          修改
        </n-button>
        <n-popconfirm
          @positive-click="removeSkuList(item._id, item.goods_id)"
        >
          <template #trigger>
            <n-button type="error" size="small" text-14 ml-5 mt5>
              <template #icon>
                <icon-material-symbols:delete-outline />
              </template>
              删除
            </n-button>
          </template>
          确定执行该操作吗？
        </n-popconfirm>
      </n-gi>
    </n-grid>
  </Cdialog>
  <Cdialog v-model:visible="skuDialog.visible" :title="skuDialog.title">
    <n-form
      ref="skuFormRef"
      :label-width="80"
      :model="skuDialog"
    >
      <n-form-item label="价格" path="price">
        <n-input-number v-model:value="skuDialog.price" :show-button="false" placeholder="输入该选项价格" w-full />
      </n-form-item>
      <n-form-item label="库存" path="stock_num">
        <n-input-number v-model:value="skuDialog.stock_num" :show-button="false" placeholder="输入该选项剩余库存" w-full />
      </n-form-item>
      <n-form-item v-for="item in dialog.skuData" :key="item.id" :label="item.k">
        <n-radio-group v-model:value="item.vId" name="name" :on-update:value="(value: number) => { skuFormSkuChange(item, value) }">
          <n-radio-button
            v-for="song in item.v"
            :key="song.id"
            :value="song.id"
          >
            <n-space align="center">
              <Cimage
                v-if="song.previewImgUrl && song.previewImgUrl?.length > 0"
                width="30"
                height="30"
                :src="song.previewImgUrl[0].url"
              />
              <span>{{ song.name }}</span>
            </n-space>
          </n-radio-button>
        </n-radio-group>
      </n-form-item>
    </n-form>
    <template #footer>
      <div f-c-c>
        <n-button mr-5 b-rd-5 size="medium" @click="skuDialog.visible = false">
          <n-icon cursor-pointer size="16">
            <icon-mdi:cancel />
          </n-icon>
          <span ml-2>取 消</span>
        </n-button>
        <n-button ml-5 b-rd-5 type="primary" size="medium" @click="submitSkuModal">
          <n-icon cursor-pointer size="16">
            <icon-mdi:checkbox-marked-circle-outline />
          </n-icon>
          <span ml-2>确 定</span>
        </n-button>
      </div>
    </template>
  </Cdialog>
</template>

<style lang="scss" scoped>
:deep(.n-form-item-label) {
  font-weight: bold;
}
</style>
